package com.zzns.web;

import com.zzns.domain.Type;
import com.zzns.domain.jqInfo;
import com.zzns.service.jqGridService;
import com.zzns.web.utils.JsonUtil;
import com.zzns.web.utils.Log.PlatformLogger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Mr.Object on 15/7/23.
 */
@Controller
@RequestMapping("/jqGrid")
public class jqGridController {

    private static final String INSERT = "add";
    private static final String UPDATE = "edit";
    private static final String DELETE = "del";

    private static final int STATUS_FALIURE = 0;
    private static final int STATUS_EXCEPTION = -1;

    @Resource
    private jqGridService jqGridService;

    /**
     * 查询
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "select", method = RequestMethod.GET)
    @ResponseBody
    public String getInfo(jqInfo request) throws IOException, IllegalAccessException {

        //
        checkRequest(request);
        //检查实体类
        ToPageRequest(request);

        List<jqInfo> list = jqGridService.selectInfo(request);
        //替换
        for(jqInfo jqInfo:list){
            jqInfo.setStock(Type.valueOf(jqInfo.getStock()));
            jqInfo.setNote(Type.valueOf(jqInfo.getNote()));
        }

        PlatformLogger.message("查询结果..."+list.size());
        Double total=0.00;
        if(!list.isEmpty())total= jqGridService.selectTotalAmt(request);

        //构造json
        String json= assembMap(list, request, total);

        return json;
    }

    /**
     * 增删改
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public String updateInfo(jqInfo request) throws IOException {

        int result;
        String falseValue="";

        PlatformLogger.message("此次操作是:" + request.getOper());

        try {

            switch (request.getOper()) {

                case INSERT:
                    result = jqGridService.insert(request);
                    break;
                case UPDATE:
                    result = jqGridService.update(request);
                    break;
                case DELETE:
                    result = jqGridService.delete(request);
                    break;
                default:
                    result = STATUS_FALIURE;

            }
        }catch(Exception e){
            PlatformLogger.error("异常",e);
            result=STATUS_EXCEPTION;
        }

        return falseValue.equals("")?"操作成功"+result:falseValue;
    }

    /**
     * 弹出框
     * @return
     */
    @RequestMapping(value = "/commit")
    @ResponseBody
    public String getDialog(){
        return "success";
    }

    /**
     * 构造返回json
     * @param list
     * @param info
     * @param total
     * @return
     * @throws IOException
     */
    private String assembMap(List list,jqInfo info,Double total) throws IOException {

        Map<String, Object> map = new HashMap<>();

        map.put("page", info.getPage());
        map.put("total", info.getParameter().getTotalPage());
        map.put("records",info.getParameter().getTotalCount());
        map.put("rows", list);

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("amt",total);
        dataMap.put("note","总金额:");
        map.put("userdata",dataMap);

        PlatformLogger.message(JsonUtil.toJson(map));

        return JsonUtil.toJson(map);

    }

    /**
     * 把分页值填充到request
     * @param request
     */
    private void ToPageRequest(jqInfo request){

           //将当前页交给ParameterPage类
           request.getParameter().setCurrentPage(request.getPage());
           request.getParameter().setPageSize(request.getRows());
       }

    /**
     *遍历一个对象，是否有""，有则转换为null,同时替换掉可能因浏览器翻译插件的问题导致的transmark
     * Date:15/2/9
     * Time:15:32
     * Author Mr.Object
     */

        public  Object checkRequest(Object object) throws IllegalAccessException {

            String transmark="<span id=\"transmark\"></span>";
            //获取class对象
            Class<?> cl=object.getClass();
            //获取域集合
            Field[] fields=cl.getDeclaredFields();
            //可以查看私有域的值
            AccessibleObject.setAccessible(fields, true);
            //循环判断
            for(Field field:fields){
                if(field.getGenericType().toString().equals("class java.lang.String")){
                    Object val=field.get(object);
                    if(val!=null && val==""){
                        if(val.toString().indexOf(transmark)>0){
                            String newVal=val.toString().replaceAll(transmark,"");
                            field.set(object,newVal);
                        }
                        field.set(object,null);
                    }

                }
            }
            return object;
        }
    }




